import React, { Component } from 'react'
import { connect } from 'dva';
import Link from 'umi/link';
import { Form, Cascader } from 'antd';
import { SearchRow, SearchCol, SearchButton } from '@/styled/form';
import { DICT } from '../enum';
import { DropDownSelectObj } from '@/components/DropDownSelect/index';
import { getBuildFn } from '@/utils/get_position';
import { UmiComponentProps, SearchComponentProps } from '@/common/type';

interface P {
  dict?: any;
  cond?: {
    ownerId: string;
    pageNum: number;
    pageSize: number;
  };
  locationData?: Array<any>;
}

const FormItem = Form.Item;

type Props = P & UmiComponentProps & SearchComponentProps;

@connect(({ risk }) => ({
  locationData: risk.locationData || {} || {},
  dict: risk.dict || {},
  optionData: risk.optionData || {},
  areaData: risk.areaData || {},
  cond: risk.todoCond || {},
}))
class Search extends Component<Props, any> {
  state = {
    option: []
  }

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'risk/deviceLocation'
    }).then(() => {
      let { locationData = [] } = this.props;
      Array.isArray(locationData) && locationData.map(item => {
        item.label = item.name;
        item.value = item.id;
        item.isLeaf = false;
        item.level = '1';
        delete item.name;
        return item;
      });
      this.setState({ option: locationData }, () => {
        const { cond, form } = this.props;
        const { pageNum, pageSize, ...searchParams } = cond;
        form.setFieldsValue(searchParams);
      })
    });

    dispatch({
      type: 'risk/queryDict',
      payload: {
        keyList: DICT
      }
    }).then(() => {
      const { cond, form } = this.props;
      const { pageNum, pageSize, ...searchParams } = cond;
      form.setFieldsValue(searchParams);
    });
  }

  loadData = (selectedOptions) => {
    const { dispatch, locationData } = this.props;
    const targetOption = selectedOptions[selectedOptions.length - 1];
    const level = targetOption.level;
    targetOption.loading = true;
    getBuildFn(level, dispatch, 'risk/optionLocation', '', targetOption, locationData, this);
  };

  private search = (e) => {
    e.preventDefault();

    const { dispatch } = this.props;
    this.props.form.validateFields((err: undefined | {}, values) => {
      if (!err) {
        const { buildList } = values;
        if (Array.isArray(buildList) && buildList.length > 0) {
          switch (buildList.length) {
            case 1: values.buildId = buildList[0]; break;
            case 2: values.floorId = buildList[1]; break;
            default:
          }
          delete values.buildList;
        }

        dispatch({
          type: 'risk/updateTodoCond',
          payload: {
            ...values
          }
        });

        this.props.initCurrent()
      }
    });
  };

  onChangeCascader = (value) => {
    let { dispatch, form, cond } = this.props;

    if ((Array.isArray(value) && value.length === 2) || (Array.isArray(value) && value.length === 0)) {
      form.validateFields((err, values) => {
        if (err) return;

        const parmas = {
          ...cond,
          ...values,
          floorId: value[1],
        }

        delete parmas.buildList

        dispatch({
          type: 'risk/updateTodoCond',
          payload: parmas
        }).then(() => {
          this.props.initCurrent()
        })
      })

      this.setState({ type: value.length === 0 ? null : value[1] })
    }
  };

  private handleChange = (type: string, value: number | string) => {
    const { cond = {}, dispatch } = this.props;
    cond[type] = value;

    dispatch({
      type: 'risk/updateTodoCond',
      payload: cond
    })
  }

  render() {
    const { form, dict = {} } = this.props;
    const { getFieldDecorator } = form;
    const formItemLayout = {
      labelCol: { span: 8 },
      wrapperCol: { span: 16 },
    };
    return (
      <Form style={{ marginTop: 20 }} onSubmit={this.search}>
        <SearchRow>
          <SearchCol key={0} span={4} >
            <FormItem
              label="处理状态"
              {...formItemLayout}
            >
              {getFieldDecorator('state')(
                DropDownSelectObj({
                  dict, type: 'risk.state.search',
                  onChange: (v) => this.handleChange('state', +v)
                })
              )}
            </FormItem>
          </SearchCol>
          <SearchCol key={1} span={4}>
            <FormItem
              label="隐患来源"
              {...formItemLayout}
            >
              {getFieldDecorator('originType')(
                DropDownSelectObj({
                  dict, type: 'risk.origin.type',
                  onChange: (v) => this.handleChange('originType', +v)
                })
              )}
            </FormItem>
          </SearchCol>

          <SearchCol key={2} span={4}>
            <FormItem
              label="建筑楼层"
              {...formItemLayout}
            >
              {getFieldDecorator('buildList', {
                rules: [{ required: false, message: '所在建筑' }],
              })(
                <Cascader
                  options={this.state.option || this.props.locationData}
                  loadData={this.loadData}
                  changeOnSelect
                  placeholder="请选择"
                  onChange={this.onChangeCascader}
                />
              )}
            </FormItem>
          </SearchCol>
          <SearchCol key={3} span={4}>
            <FormItem
              label="是否逾期"
              {...formItemLayout}
            >
              {getFieldDecorator('overdue')(
                DropDownSelectObj({
                  dict, type: 'risk.overdue',
                  onChange: (v) => this.handleChange('overdue', +v)
                })
              )}
            </FormItem>
          </SearchCol>
          <SearchCol key={4} span={8} >
            <SearchRow type="flex" justify="end" style={{ marginRight: '10px' }}>
              <SearchButton icon='redo'  onClick={() => {
                this.props.form.resetFields();
              }} style={{ 'marginLeft': '15px' }}>重置</SearchButton>
                <SearchButton htmlType="submit" icon='search' type="primary">搜索</SearchButton>
              {this.props.new && <Link to='/data/risk/new' style={{ marginLeft: '15px' }}>
                <SearchButton icon='plus' type="primary">新增</SearchButton>
              </Link>}
            </SearchRow>
          </SearchCol>
        </SearchRow>
      </Form>
    );
  }
}

const SearchS = Form.create<Props>()(Search);
export default SearchS;
